<template>
  <div class="rwt-split-area">
    <div class="wrapper">
      <div :class="[`rn-splite-style`, 'bg-color-blackest']">
        <div class="split-wrapper">
          <div class="row no-gutters radius-10 align-items-center">
            <div
              :class="[`col-lg-12 col-xl-6 col-12`, 'order-2']"
              style="position: relative"
            >
              <!--                            单张图片-->
              <div class="process" v-if="!isshow2 && isshow">
                <el-progress
                  class="asprogress"
                  :stroke-width="10"
                  :percentage="percent"
                ></el-progress>
              </div>
              <div class="process" v-if="isshow2 && !isshow">
                <el-progress
                  class="asprogress"
                  :stroke-width="10"
                  :percentage="percent2"
                  v-show="isshow2"
                ></el-progress>
              </div>
              <div
                class="thumbnail"
                v-if="
                  resImage.length === 0 && this.isshow === false && !isshow2
                "
                style="height: 100%"
              >
                <el-image
                  style="width: 700px; height: 700px"
                  :src="defaultImg"
                  fit="cover"
                />
              </div>
              <div
                v-if="
                  resImage.length !== 0 && this.isshow === false && !isshow2
                "
                style="width: 660px"
              >
                <!--                            列表轮播，用户请求了一组图片-->
                <el-carousel
                  trigger="click"
                  height="720px"
                  :autoplay="false"
                  ref="carousel"
                  indicator-position="outside"
                >
                  <el-carousel-item
                    v-for="(item, index) in resImage"
                    :key="index"
                    :name="item.query"
                  >
                    <div
                      class="opBtn"
                      @click="showOp = true"
                      v-if="!showOp"
                      style="
                        position: relative;
                        top: -4px;
                        margin-top: 4px;
                        height: 50px;
                      "
                    >
                      <i class="el-icon-s-operation"></i>
                    </div>
                    <div
                      class="opBox"
                      v-if="showOp && resImage.length !== 0"
                      style="
                        position: relative;
                        top: -4px;
                        margin-top: 4px;
                        height: 50px;
                      "
                    >
                      <el-color-picker
                        v-model="color"
                        @active-change="changeColor"
                        show-alpha
                      />
                      <div class="button-group" v-if="match" @click="showMatch">
                        <Button
                          title="比对变化前"
                          size="small"
                          :outlined="true"
                        />
                      </div>
                      <div class="button-group" v-else @click="showMatch">
                        <Button
                          title="比对变化后"
                          size="small"
                          :outlined="true"
                        />
                      </div>
                      <div class="button-group" @click="cover = false">
                        <Button
                          title="只看结果"
                          size="small"
                          :outlined="true"
                        />
                      </div>
                      <div class="button-group" @click="showImgModal(item)">
                        <Button
                          title="对比查看"
                          size="small"
                          :outlined="true"
                        />
                      </div>
                      <div>
                        <div class="button-group" @mouseenter="download = true">
                          <Button
                            title="下载结果"
                            size="small"
                            :outlined="true"
                          />
                        </div>
                        <ul
                          class="download"
                          v-if="download"
                          @mouseleave="download = false"
                        >
                          <li>
                            <div
                              class="button-group"
                              @click="downloadImage(item, 1)"
                            >
                              <Button
                                title="黑色底图"
                                size="small"
                                :outlined="true"
                              />
                            </div>
                          </li>
                          <li>
                            <div
                              class="button-group"
                              @click="downloadImage(item, 2)"
                            >
                              <Button
                                title="透明底图"
                                size="small"
                                :outlined="true"
                              />
                            </div>
                          </li>
                          <li
                            style="
                              display: flex;
                              flex-direction: row;
                              width: 250px;
                            "
                          >
                            <div
                              class="button-group"
                              @mouseenter="download2 = true"
                              style="margin-top: 0px"
                            >
                              <Button
                                title="包含原图"
                                size="small"
                                :outlined="true"
                              />
                            </div>
                            <ul
                              v-if="download && download2"
                              @mouseleave="download2 = false"
                              style="padding: 5px"
                            >
                              <div
                                class="button-group"
                                @click="downloadImage(item, 3)"
                                style="margin-left: -10px"
                              >
                                <Button
                                  title="变化前"
                                  size="small"
                                  :outlined="true"
                                />
                              </div>
                              <div
                                class="button-group"
                                @click="downloadImage(item, 4)"
                                style="margin-left: -10px"
                              >
                                <Button
                                  title="变化后"
                                  size="small"
                                  :outlined="true"
                                />
                              </div>
                            </ul>
                          </li>
                        </ul>
                      </div>
                      <div>
                        <div class="button-group" @mouseenter="moreFunc = true">
                          <Button
                            title="更多功能"
                            size="small"
                            :outlined="true"
                          />
                        </div>
                        <ul
                          class="download"
                          v-if="moreFunc"
                          @mouseleave="moreFunc = false"
                        >
                          <li
                            v-for="(item, index) in splitData.links"
                            :key="index"
                          >
                            <div
                              class="button-group"
                              @click="switchFunc(item.funcLink)"
                            >
                              <Button
                                :title="item.funcName"
                                size="small"
                                :outlined="true"
                              />
                            </div>
                          </li>
                        </ul>
                      </div>
                      <div class="opBtn2" @click="showOp = false">
                        <i class="el-icon-d-arrow-left"></i>
                      </div>
                    </div>
                    <div
                      class="thumbnail"
                      style="position: relative; height: 100%"
                      id="show-img"
                    >
                      <!-- 原图 -->
                      <img
                        v-if="cover && !match"
                        :src="item.query"
                        alt="Split Image"
                        style="position: absolute"
                      />
                      <img
                        v-if="cover && match"
                        :src="item.match"
                        alt="Split Image"
                        style="position: absolute"
                      />
                      <!-- 纯黑图 -->
                      <img
                        v-if="!cover"
                        :src="blackImg"
                        alt="Split Image"
                        style="position: absolute"
                      />
                      <!-- 结果图 -->
                      <span
                        class="result-image"
                        :style="{
                          WebkitMask: 'url(' + item.result + ') space',
                          backgroundColor: color,
                        }"
                      ></span>
                    </div>
                  </el-carousel-item>
                </el-carousel>
              </div>
            </div>
            <div
              :class="[`col-lg-12 col-xl-6 col-12`, 'order-1']"
              style="min-width: 750px"
            >
              <div class="split-inner">
                <div style="display: flex; flex-direction: row">
                  <h4 class="title">{{ splitData.title }}</h4>
                  <Button
                    :read-more-button="true"
                    style="margin-left: 30px; margin-top: 15px"
                    v-for="(item, index) in splitData.links"
                    :key="index"
                    :url="item.funcLink"
                  >
                    <span @click="obtainList = true">{{ item.funcName }}</span>
                  </Button>
                </div>
                <p class="description">{{ splitData.description }}</p>
                <div style="display: flex; flex-direction: row">
                  <!--                                    上传图片组件-->
                  <CDPhotoList
                    ref="cdPhotoList"
                    @handleRemove="removeResItem"
                    @showTarget="showSingleRes"
                  />
                </div>
                <div
                  style="display: flex; flex-direction: row; margin-top: 20px"
                >
                  <button class="btn-default" @click="showResult">
                    运行全部
                  </button>
                  <button
                    style="margin-left: 30px"
                    class="btn-default"
                    @click="callDrawer"
                  >
                    打开图片库
                  </button>
                  <Button
                    :read-more-button="true"
                    style="margin-left: 30px; margin-top: 15px"
                  >
                    <span @click="resetImg">清空图片</span>
                  </Button>
                  <Button
                    :read-more-button="true"
                    style="margin-left: 30px; margin-top: 15px"
                  >
                    <span @click="runDemo">示例图片</span>
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <ImgDialog ref="imgmodal" />
  </div>
</template>

<script>
    import Layout from '../common/Layout'
    import Split from "../elements/split/Split";
    import ImgDialog from "../modal/ImgDialog";
    import Button from "../elements/button/Button";
    import CDPhotoList from "./CDPhotoList";
    import eventBus from "../../global/eventBus";
    // import qs from 'qs'
    export default {
        name: "CDUploadPic",
        components:{Button, CDPhotoList, ImgDialog, Layout,Split},
        data(){
            return{
                moreFunc:false,
                obtainList:false,//跳转来时是否保存列表
                download:false,
                download2:false,//二级菜单
                match:false,
                showOp:true,//是否有返回的结果（一张或者一组），决定是否展示对于图片的操作菜单
                cover:false,//是否显示原图叠加结果
                loading:false,//是否正在加载
                uid:this.$ls.get('userInfo')===null?'':this.$ls.get('userInfo').id,
                resImage:[], //返回的图片
                defaultImg:'',//默认图片、结果存放
                blackImg: 'https://cdn.bewcf.info/softwareCup/554bea32-5dd5-44d0-9511-5b4b3084821d.png',//默认纯黑图（底图）
                color:'rgba(255, 255, 255, 1)', //结果图片颜色
                percent:0,
                percent2:0,
                isshow: false,
                isshow2:false,
            }
        },
        props: {
            splitData: {
                image:'',
                // url:'',
                title: '',
                description: '',
                links:[]
            }
        },
        created() {
            // var that = this
            this.defaultImg=require('../../assets/images/functions/'+this.splitData.image)
            this.$on('setItem',data=>{
                // console.log('在setItem')
                this.$nextTick(function () {
                    this.$refs.carousel.setActiveItem(data)
                })
            })
            this.$on('downloadImg',data=>{
                let image = new Image();
                // 解决跨域 Canvas 污染问题
                image.setAttribute("crossOrigin", "anonymous");
                image.onload = function () {
                    let canvas = document.createElement("canvas");
                    canvas.width = image.width;
                    canvas.height = image.height;
                    let context = canvas.getContext("2d");
                    context.drawImage(image, 0, 0, image.width, image.height);
                    let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
                    let a = document.createElement("a"); // 生成一个a元素
                    let event = new MouseEvent("click"); // 创建一个单击事件
                    var name = data.split('/')
                    a.download = name[name.length-1] // 设置图片名称
                    a.href = url; // 将生成的URL设置为a.href属性
                    a.dispatchEvent(event); // 触发a的单击事件
                };
                image.src=data
            })
        },
        mounted() {
            this.resImage=this.$ls.get('resImage2',[])
        },
        beforeDestroy() {
            // console.log('在beforeDestroy')
            if(this.obtainList){
                this.$ls.set('fileList',this.$refs.cdPhotoList.fileList)
                this.$ls.set('fileList2',this.$refs.cdPhotoList.fileList2)
                this.$ls.set('resImage2',this.resImage)
            }else {
                this.$ls.remove('fileList')
                this.$ls.remove('fileList2')
                for(var i=1;i<=4;++i){
                    this.$ls.remove('resImage'+i)
                }
            }
        },
        methods:{
            switchFunc(url){
                // console.log('在切换功能')
                this.obtainList=!this.obtainList
                this.$router.push({name:url})
            },
            callDrawer(){
                eventBus.$emit('callDrawer',true)
            },
            downloadImage(item,index) {
                // console.log('在下载')
                const paramData={}
                paramData.result=item.result
                paramData.rgba = this.color
                switch (index) {
                    // 黑色底图
                    case 1:
                        paramData.file=''
                        break
                    // 透明底图
                    case 2:
                        paramData.transparent=1
                        break
                    case 3://变化前
                        paramData.file=item.query
                        break
                    case 4://变化后
                        paramData.file=item.match
                        break
                    default:break
                }
                this.$axios.post(this.$global.apiUrl+'file/overlay',null,{params:paramData
                }).then(res=>{
                    // console.log(res.data)
                    this.$emit('downloadImg',res.data.data)
                }).catch(error=>{
                    console.log(error)
                    that.$message.error('网络错误，稍后再试');
                })
            },
            showMatch(){
                // console.log(this.resImage)
                this.match=!this.match
                this.cover=true
            },
            removeResItem(file){
                this.resImage.forEach(item=>{
                    if(file.url===item.query||file.url===item.match){
                        this.resImage.splice(this.resImage.indexOf(item),1)
                    }
                })
            },
            changeColor(e) {
                this.color = e
            },
            //接收单张图片请求
            showSingleRes(data){
                // console.log('在请求某一张')
                if(this.$refs.cdPhotoList.fileList.length!==this.$refs.cdPhotoList.fileList2.length){
                    this.$message.error('请上传成对图片');
                    return
                }
                if(this.resImage.length!==0&&this.isAlreadyChecked(data.url)){//结果列表中已经有这个结果
                    this.$refs.carousel.setActiveItem(data.url)
                }else { //没有请求过
                    var url=this.$global.apiUrl+'ai/changeDetection'
                    this.isshow2=true
                    this.percent2=0
                    var that = this
                    var file2=this.$refs.cdPhotoList.fileList2[this.$refs.cdPhotoList.fileList.indexOf(data)]
                    this.$axios.post(url, null, { params: {
                            file1:data.url4req,
                            file2:file2.url4req,
                            userId:that.uid
                        }})
                        .then(res=>{
                            var temp={
                                query:data.url,
                                match:file2.url,
                                result:res.data.data
                            }
                            // that.resImage.push(temp)
                            that.processOn2(temp)
                            that.loading=false//结束加载状态
                            setTimeout(()=>{
                                    this.$emit('setItem',data.url)},
                                3000)
                        }).catch(function(error) {
                        console.log(error);
                        that.$message.error('网络错误，稍后再试');
                    });
                }
            },
            //改变进度条状态
            processOn(data){
                // 这里不知道为什么要加一才行

                this.percent=parseInt((this.resImage.length+1)/this.$refs.cdPhotoList.fileList.length*100)
                this.resImage.push(data)
                if(this.percent2>=100||this.percent>=100){
                    // console.log("mounted");
                    var a=0;
                    var id=setInterval(()=>{
                        a=this.percent;
                        // console.log("a is"+a+typeof a);
                        if(a===100){
                            clearInterval(id);
                            this.isshow = false;
                            this.isshow2 = false;
                            this.percent=0
                            // console.log("执行了clearInterval函数");
                        }
                    },1000);
                    this.percent=100;//结束加载状态
                    //setTimeout(this.isshow=false,30000);
                    this.$message({
                        message: '请求成功！',
                        type: 'success'
                    });
                    this.showOp=true
                    return this.percent;
                }
            },
            processOn2(data) {
                // 这里不知道为什么要加一才行
                this.percent2 = 100
                this.percent = parseInt((this.resImage.length + 1) / this.$refs.cdPhotoList.fileList.length * 100)
                this.resImage.push(data)
                if (this.percent2 >= 100) {
                    // console.log("mounted");
                    var a = 0;
                    var id = setInterval(() => {
                        a = this.percent > this.percent2 ? this.percent : this.percent2;
                        this.percent2 = 0;
                        // console.log("a is" + a + typeof a);
                        if (a === 100) {
                            clearInterval(id);
                            this.isshow = false;
                            this.isshow2 = false;
                            // console.log("执行了clearInterval函数");
                        }
                    }, 1000);
                    //this.percent=100;//结束加载状态
                    //setTimeout(this.isshow=false,30000);
                    this.$message({
                        message: '请求成功！',
                        type: 'success'
                    });
                    return this.percent;
                }
            },
            // 示例图片
            runDemo() {
                this.$refs.cdPhotoList.runDemo()
            },
            showResult(){
                if(this.$refs.cdPhotoList.fileList.length!==this.$refs.cdPhotoList.fileList2.length){
                    this.$message.error('请上传成对图片');
                    return
                }
                if(this.$refs.cdPhotoList.fileList.length===0){
                    this.$message.error('请上传图片');
                    return
                }
                if(this.isLoading(this.$refs.cdPhotoList.fileList)||this.isLoading(this.$refs.cdPhotoList.fileList2)){
                    this.$message.error('您操作太快了，请等待图片上传完成');
                    return
                }
                this.loading=true
                this.getOneResult(0)
            },
            getOneResult(i) {
                let that = this;
                while(this.isAlreadyChecked(that.$refs.cdPhotoList.fileList[i].url)){
                    i++;
                    if(i>this.$refs.cdPhotoList.fileList.length-1){
                        return
                    }
                }
                this.isshow = true;
                this.isshow2 = false;
                let item = that.$refs.cdPhotoList.fileList[i]
                var file2=this.$refs.cdPhotoList.fileList2[this.$refs.cdPhotoList.fileList.indexOf(item)]
                var url=this.$global.apiUrl+'ai/changeDetection'
                this.$axios.post(url, null, { params: {
                        file1:item.url4req,
                        file2:file2.url4req,
                        userId:that.uid
                    }})
                    .then(res=>{
                        var temp={
                            query:item.url,
                            match:file2.url,
                            result:res.data.data
                        }
                        this.processOn(temp)
                        i++;
                        if (i < that.$refs.cdPhotoList.fileList.length) {
                            that.getOneResult(i)
                        }
                    }).catch(function(error) {
                    console.log(error);
                    that.$message.error('网络错误，稍后再试');
                });
            },
            isAlreadyChecked(url){
                var flag=false
                this.resImage.forEach(item=>{
                    if(item.query===url){
                        // console.log('已经在了')
                        flag = true
                    }
                })
                return flag
            },
            // 清空图片
            resetImg(){
                this.resImage=[]
                this.defaultImg=require('../../assets/images/functions/'+this.splitData.image)
                this.$refs.cdPhotoList.fileList=[]
                this.$refs.cdPhotoList.fileList2=[]
                // this.showOp=false
                this.percent = 0;
                this.percent2 = 0;
                this.$ls.remove('fileList')
                this.$ls.remove('fileList2')
                for(var i=1;i<=4;++i){
                    this.$ls.remove('resImage'+i)
                }
            },
            showImgModal(item){
                this.$refs.imgmodal.query = this.match?item.match:item.query
                this.$refs.imgmodal.result = item.result
                if (this.opType === 3) this.$refs.imgmodal.result = item.result.url
                this.$refs.imgmodal.cover = this.cover
                this.$refs.imgmodal.color = this.color
                // console.log(item.result)
                this.$refs.imgmodal.show();
            },
            isLoading(fileList){
                var flag=false
                fileList.forEach(item=>{
                    if(item.loading){
                        flag=true
                    }
                })
                return flag
            }
        }
    }
</script>

<style>
@-webkit-keyframes mymove {
  /* Safari and Chrome */
  0% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}
#show-img {
  width: 660px;
  height: 660px;
}

#show-img img {
  height: 100%;
  width: 100%;
  object-fit: contain;
}
.asprogress {
  /*background: rgba(255,255,255,0.1);*/
  width: 80%;
  margin-left: 10%;
  height: 600px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.asprogress .el-progress-bar__inner {
  content: "";
  width: 100%;
  height: 100%;
  display: block;
  background-color: transparent;
  background-image: linear-gradient(to right, #6549d5, #fb5343, #e33fa1);
}
.opBtn {
  position: absolute;
  top: 0;
  left: 0;
  height: 30px;
  width: 30px;
  z-index: 9;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.7);
  background: rgba(127, 127, 127, 0.5);
  font-size: 20px;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}
.opBtn2 {
  font-size: 30px;
  color: #e7e6e6;
  margin-top: -5px;
}
.opBox {
  position: absolute;
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: space-around;
  width: 100%;
  height: 50px;
  top: 0;
  /*bottom: 50px;*/
  padding-top: 5px;
  left: 0;
  z-index: 9;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.7);
  background: rgba(127, 127, 127, 0.5);
}

.result-image {
  height: 100%;
  width: 100%;
  position: absolute;
  display: inline-block;
  background-color: #ffffff;
  mask: url(https://cdn.bewcf.info/softwareCup/e944fccc-c8e4-4340-af57-129918a193b8.png)
    no-repeat;
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
  mask-size: contain !important;
  mask-position: center !important;
}

.download {
  position: relative;
  top: -5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.7);
  background: rgba(127, 127, 127, 0.5);
  width: 100px;
  padding: 0;
  padding-left: 5px;
  height: 180px;
  border-radius: 5px;
}

.download .button-group a {
  width: 90px;
  padding: 0 !important;
}

.download li {
  list-style-type: none;
}
.download li ul {
  border-radius: 5px;
  margin-left: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.7);
  background: rgba(127, 127, 127, 0.5);
}
</style>
